package chapter_24.udp.chat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;

/**
 * Created by Administrator
 * Created time 2018/8/10 15:53.
 * 案例:聊天工具(服务端)
 */
public class ChatServer {

    public static void main(String[] args) {

        System.out.println("服务端运行...");

        Thread server = new Thread(() -> {

            try (// 创建一个 ServerSocket 监听端口客户请求
                 DatagramSocket datagramSocket = new DatagramSocket(6666);
                 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in))
            ) {

                while (true) {
                    /*
                     接收数据报
                     */
                    // 缓冲区
                    byte[] bytes = new byte[1024];
                    DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length);
                    datagramSocket.receive(datagramPacket);
                    // 接收数据长度
                    int len = datagramPacket.getLength();

                    String str = new String(bytes, 0, len);
                    // 打印接收的数据
                    System.out.printf("从客户端接收的数据: [%s] \n", str);

                    /*
                     发送数据
                     */
                    // 从客户端传来的数据报包得到客户端地址
                    InetAddress address = datagramPacket.getAddress();
                    // 从客户端传来的数据报包得到客户端端口号
                    int port = datagramPacket.getPort();

                    // 读取键盘输入的字符串
                    String keyboardInputStr = bufferedReader.readLine();
                    // 读取键盘输入的字节数组
                    byte[] b = keyboardInputStr.getBytes();
                    // 创建 DatagramPacket 对象,用于向客户端发送数据
                    datagramPacket = new DatagramPacket(b, b.length, address, port);
                    // 向客户端发送数据
                    datagramSocket.send(datagramPacket);
                }
            } catch (ConnectException e) {
                System.out.println("服务器未启动!");
            } catch (SocketException e) {
                System.out.println("SocketException");
            } catch (UnknownHostException e) {
                System.out.println("UnknownHostException");
            } catch (IOException e) {
                System.out.println("IOException");
            }

            System.out.println("服务器停止!");
        });

        server.start();
    }
}